package com.jinly.ryder.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SshKeyUtil {

    public static String getPriKeyFileName(String priKey) {
        if (ObjectUtils.isEmpty(priKey)) return null;
        String md5 = DigestUtils.md5DigestAsHex(priKey.getBytes());
        String fileName = System.getProperty("user.home") + "/.ssh/id_" + md5;
        if (!FileUtil.existsFile(fileName)) {
            FileUtil.createFile(fileName, priKey.getBytes());
            try {
                Process process = Runtime.getRuntime().exec("chmod 0600 " + fileName);
                process.waitFor(5, TimeUnit.SECONDS);
                if (process.exitValue() != 0) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        log.error("=>{}", line);
                    }
                }
            } catch (Exception e) {
                log.error("chmod error:", e);
            }
        }
        return fileName;
    }
}
